<?php
namespace app\admin\controller\soft;
use app\admin\Adminbase;
use think\Image;
use OSS\OssClient;
use OSS\Core\OssException;

class Upload extends Adminbase 
{
	
	protected $tableName = 'xw_system_upload';  			//表名
	
	/**
    * 上传接口
    * /soft/upload/upload 
    * @access public
    * @param string $fkGuid 		
    * @param string $ywName 		
    * @param string $fkType 		
    * @return  array
    */
	public function upload($fkGuid='',$ywName='',$fkType='',$desc='',$classify_id=0){
		if( empty($fkGuid) )
			throw new \think\Exception('fkGuid不能为空');
		if( empty($ywName) )
			throw new \think\Exception('ywName不能为空');
		if( empty($fkType) )
			throw new \think\Exception('fkType不能为空');
	
		$files = request()->file();
		$fileId = 0;
	    foreach($files as $file){
			
			//保存的数据
			$data = [];
			
			//文件信息
	    	$fileInfo = $file->getInfo();
			$fileType = $fileInfo['type'];
			$fileName = $fileInfo['name'];
			$tmpName = $fileInfo['tmp_name'];
			$fileSize = $fileInfo['size'];
			$fileExt = substr($fileName,strrpos($fileName,'.')+1); 
			
            $config = env('SYSTEM_BASE_CONFIG_FILE');
			if($config["type"] == 'oss'){
		        try {
		        	@error_reporting (E_ALL & ~E_NOTICE & ~E_WARNING);
			     	$keyId = $config['accessKeyId'];
			        $keySecret = $config['accessKeySecret'];
			        $endpoint = $config['endpoint']; 
			        $catalog= $config['catalog'];
			        $auth = new OssClient($keyId,$keySecret,$endpoint);
			        $dst = $catalog.date('ymd').'/'.md5(time()).''.'-'.$fileName;  
		            $result = $auth->uploadFile($config['bucket'],$dst,$tmpName);
					$info = $result['info'];
					$filePath =  $info['url'];
					$data['duration'] = $info['total_time']; //这个获得的便是音频文件的时长
		        } catch (OssException $e) {
		        	return $this->ReError($e->getMessage());
		        }
			}else{
				if(!is_dir("uploads")) mkdir("uploads"); 
				if( !$info = $file->move('uploads') ) {
					return $this->ReError( $file->getError() );
				}
				$filePath =  $info->getPathName();
				//如果是图片就压缩
				if(strstr($filePath,".jpg") || strstr($filePath,".png")){
					$image = Image::open($info);
					$image->thumb(2650, 2650)->save($filePath); 
					$data['width'] = $image->width();
					$data['height'] = $image->height();
				}
				//如果是音频就获取时长
				if(strstr($filePath,".mp3") || strstr($filePath,".mp4")){
					include_once( base_path().'/extend/lib/getid3/getid3.php');
					$getID3 = new \getID3();
					$thisFileInfo = $getID3->analyze($filePath); //分析文件，$path为音频文件的地址
					$data['duration'] = $thisFileInfo['playtime_seconds']; //这个获得的便是音频文件的时长
				}
			}
			
			$data['file_name']= $fileName;
	    	$data['file_path']=  $filePath;
	    	$data['file_guid']= "$fkGuid";
	    	$data['file_type']= "$fkType";
	    	$data['file_buss_type']= "$ywName";
	    	$data['file_description']="$desc";
	    	$data['type']= $fileType;
	    	$data['size']= $fileSize;
	    	$data['ext']= $fileExt;
	    	$data['classify_id']= $classify_id;
	    	$fileId =  \Db::table(  $this->tableName )->insertGetId($data);
	    }

		if($fileId){
			if( strstr($data['file_path'],"http://") ||  strstr($data['file_path'],"https://") ){
				$file_path = $data['file_path'];
			}else{
				$file_path = APP_PATH.'/'.str_replace("\\","/",$data['file_path']);
			}
			return $this->ReSucess(["id"=> $fileId,"src"=>$file_path],'上传成功！');
		}else{
			return $this->ReError('上传失败！');
		}
		
	}

	
    /**
    * 获取附件
    * /admin/soft/upload/getFileList 
    * @access public
    * @param string $fkGuid 		
    * @param string $ywName 		
    * @param string $fkType 		
    * @return  array
    */
	public function getFileList($fkGuid,$ywName,$fkType){
		$data = \Db::table( $this->tableName )
			->where("file_guid='$fkGuid' and file_buss_type = '$ywName' and file_type= '$fkType' ")
			->field("*")
			->order('is_default desc,create_time')
			->select();
			
    	return $this->ReSucess($data,'');
	}
	
	
	/**
    * 获取附件列表
    * /admin/soft/upload/getClassifyFileList 
    * @access public
    * @param string $fkGuid 		
    * @param string $ywName 		
    * @param string $fkType 		
    * @return  array
    */
	public function getClassifyFileList($classify_ids,$name='',$page=1,$limit=20){
		$model = \Db::table( $this->tableName )
			->where("classify_id",'in',$classify_ids)
			->where("file_name",'like',"%$name%")
			->order('is_default desc,create_time desc');
			
		$data = [
			'count'=>$model->count(),
			'list'=> $model->page($page,$limit)->select()
		];	
		
    	return $this->ReSucess($data,'');
	}
	
	/**
    * 删除附件
    * /admin/soft/upload/deleteFile 
    * @access public
    * @param string $fileIds 		
    * @return  array
    */
	public function deleteFile($fileIds){
		$result = \Db::table( $this->tableName )->where("file_id","in",$fileIds)->select();
		if(!$result){
			return $this->ReError("file_id不存在");
		}else{
			foreach ($result as $fies){
				$savepath = str_replace(__ROOT__,'.',$fies['file_path']);
				@unlink($savepath);//删除文件
			}
			\Db::table( $this->tableName )->where("file_id","in",$fileIds)->delete();
		}
		return $this->ReSucess($result,'');
	}
	
	/**
    * 设置默认
    * /admin/api/upload/setDefault 
    * @access public
    * @param string $file_id 		
    * @param string $type   1=默认, 0 等于取消默认		
    * @return  array
    */
	public function setDefault($file_id,$type){
		if(!$file_id || (!$type && $type !=='0') ){
			return $this->ReError("参数错误");
		}
		$file_guids = \Db::table($this->tableName)->where("file_id","=",$file_id)->column('file_guid');
		if(!$file_guids[0]){
			return $this->ReError("文件不存在");
		}
		\Db::table($this->tableName)->where("file_guid",$file_guids[0])->update(["is_default"=>0]);
		$result = \Db::table($this->tableName)->where("file_id",$file_id)->update(["is_default"=>$type]);
		if($result === false){
			return $this->ReError("操作失败");
		}
		return $this->ReSucess();
	}
	
	/**
    * 下载
    * /admin/soft/upload/downloadHandler 
    * @access public
    * @param string 		$file_id 		
    * @param Boolean 	$is_ziz 		
    * @return  array
    */
	public function downloadHandler($file_id,$is_ziz=false){
		$data = \Db::table($this->tableName)->where("file_id","in",$file_id)->select();
		if(!$data[0]){
			return $this->ReError("文件不存在！");
		}else{
			$files=[];
			foreach ($data as $fies){
				$fileExt= $fies['ext'];
				$savepath = str_replace(APP_PATH,'.',$fies['file_path']);
				$fileName = str_replace('.'.$fileExt,'',$fies['file_name']);
				$fileName = iconv('utf-8', 'gb2312', $fileName);//文件名称
				$files[]=$savepath;
				$filePath = realpath($savepath);
				$fp = fopen($filePath, 'rb');
				if (!$filePath || !$fp) {
					header('HTTP/1.1 404 Not Found');
					echo "
						Error: 404 Not Found.(server file path error)
						</br>
						</br>
						【 $fileName 】文件不存在，或已被删除
					";
					exit;
				}
				if(!$is_ziz){
					if( 
						strstr($savepath, '.png') ||  
						strstr($savepath, '.jpeg')  || 
						strstr($savepath, '.bmp') || 
						strstr($savepath, '.gif') 
					){
						
						$filePath  = str_replace( "./" , "/",$fies['file_path'] );
						
						if($size = request()->get('size')){
							$minFilePath = str_replace(".","_{$size}.",$filePath);
					    	$image = Image::open($filePath);
							$image->thumb($size, $size)->save(public_path().'/'. $minFilePath); 
							$filePath = $minFilePath;
						}
						
						$this-> echo_imagedestroy( public_path().'/'. $filePath );
						
					}else{
						$this->download($savepath,$fileName);
					}
				}
			}
			if($is_ziz){
				include_once("extend/base/files/Zip.php");
				$dodozip = new \PHPzip; 
				$zipname = "download.zip";
				$dodozip -> zip($files,$zipname);
				header('Content-Type: application/zip');
				header('Content-disposition: attachment; filename='.$zipname);
				header('Content-Length: ' . filesize($zipname));
				readfile($zipname);
				@unlink($zipname);
			}
		}
	}
	
	/**
    * 输出图片
    * @access private
    * @param string $file 		
    * @param string $name 		
    * @return  array
    */
	private function echo_imagedestroy($img) {
		$info = getimagesize($img);
	    $imgExt = image_type_to_extension($info[2], false);  //获取文件后缀
	    $fun = "imagecreatefrom{$imgExt}";
	    $imgInfo = $fun($img);   
		$mime = "";      
		if( strstr($img, '.png') !=-1)  $mime = 'png';
		if( strstr($img, '.jpeg') !=-1)  $mime = 'jpeg';
		if( strstr($img, '.bmp') !=-1)  $mime = 'bmp';
		if( strstr($img, '.gif') !=-1)  $mime = 'gif';
	    header('Content-Type:'.$mime);
	    $quality = 100;
	    if($imgExt == 'png') $quality = 9;        //输出质量,JPEG格式(0-100),PNG格式(0-9)
	    $getImgInfo = "image{$imgExt}";
	    $getImgInfo($imgInfo, null, $quality);    //2.将图像输出到浏览器或文件
	    imagedestroy($imgInfo);
	    die;
	}
	
	/**
    * 下载方法
    * @access private
    * @param string $file 		
    * @param string $name 		
    * @return  array
    */
	private function download($file, $name = '') {
		$fileName = $name ? $name : pathinfo($file, PATHINFO_FILENAME);
		$filePath = realpath($file);
		$fp = fopen($filePath, 'rb');
		if (!$filePath || !$fp) {
			header('HTTP/1.1 404 Not Found');
			echo "
				Error: 404 Not Found.(server file path error)</br>
				文件不存在，或已被删除
			";
			exit ;
		}
		$fileName = $fileName . '.' . pathinfo($filePath, PATHINFO_EXTENSION);
		$encoded_filename = urlencode($fileName);
		$encoded_filename = str_replace("+", "%20", $encoded_filename);
		header('HTTP/1.1 200 OK');
		header("Pragma: public");
		header("Expires: 0");
		header("Content-type: application/octet-stream");
		header("Content-Length: " . filesize($filePath));
		header("Accept-Ranges: bytes");
		header("Accept-Length: " . filesize($filePath));
		$ua = $_SERVER["HTTP_USER_AGENT"];
		if (preg_match("/MSIE/", $ua)) {
			header('Content-Disposition: attachment; filename="' . $encoded_filename . '"');
		} else if (preg_match("/Firefox/", $ua)) {
			header('Content-Disposition: attachment; filename*="utf8\'\'' . $fileName . '"');
		} else {
			header('Content-Disposition: attachment; filename="' . $fileName . '"');
		}
		fpassthru($fp);
		exit ;
	}

	/**
    * 获取描述
    * /admin/soft/upload/getDesc 
    * @access public
    * @return  array
    */
	public function getDesc($file_path){
		if(!$file_path){
			return $this->ReError("参数错误");
		}
		$file_path = str_replace(APP_PATH.'/',"",$file_path);
		$file_path = str_replace('/',"\\",$file_path);
		$desc = \Db::table($this->tableName)->where("file_path",$file_path)->value('file_description');
		return $this->ReSucess($desc ?: '');
	}
	
	/**
    * 更新描述
    * /admin/soft/upload/updateDesc 
    * @access public
    * @return  array
    */
	public function updateDesc($file_path,$desc){
		if(!$file_path || !$desc){
			return $this->ReError("参数错误");
		}
		$file_path = str_replace(APP_PATH.'/',"",$file_path);
		$file_path = str_replace('/',"\\",$file_path);
		\Db::table($this->tableName)->where("file_path",$file_path)->update([
			'file_description'=>$desc
		]);
		return $this->ReSucess();
	}
	
	/**
    * 更新名称
    * /admin/soft/upload/updateName
    * @access public
    * @return  array
    */
	public function updateName($file_id,$name){
		\Db::table($this->tableName)->where("file_id",$file_id)->update(['file_name'=>$name]);
		return $this->ReSucess();
	}
	
}